<script setup>
import { CaretDownOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import JSZip from 'jszip'
import saveAs from 'jszip/vendor/FileSaver.js'
import {getCurrentInstance} from "vue";
import { isLogin } from '~/logic'

const emit = defineEmits(['login'])
const instance = getCurrentInstance()
/**
 * @type ItemInterface
 */
const item = instance.appContext.config.globalProperties.$item
const __option = getCurrentInstance()?.appContext.provides.option;
const canvas = ref(null);

const joinImages = async(urls) => {
  return new Promise( async(resolve, reject) => {
    const loadImages = async (urls) => {
      const promises = urls.map(url => {
        return new Promise((resolve, reject) => {
          const img = new Image();
          img.crossOrigin = "'crossOrigin', 'anonymous'";
          img.src = url;
          img.onload = () => resolve(img);
          img.onerror = reject;
        });
      });
      return Promise.all(promises);
    };
    const drawImages = (imgs) => {
      if (!canvas.value) return;
      const ctx = canvas.value.getContext('2d');
      if (!ctx) return;
      let yOffset = 0;
      let height = imgs.reduce((acc, img) => acc + img.height, 0);
      canvas.value.height = height;
      imgs.forEach(img => {
        ctx.drawImage(img, 0, yOffset, 750, img.height);
        yOffset += img.height;
      });
      return canvas.value.toDataURL('image/png')
    };
    const imgs = await loadImages(urls);
    const canvasUrl = await drawImages(imgs);
    if (canvasUrl) {
      resolve(canvasUrl)
    }else {
      reject('图片合并失败')
    }
  })
}

const pcDownload = [
  {
    name: '下载全部(归类)',
    tips: '一次性下载商品主图、主图视频、SKU图片、详情图片,所有资源在多个文件夹内',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return
      const loading = instance.proxy.$refs.loading
      loading.show('正在下载全部...')
      loading.update(0)
      const zip = new JSZip()
      const images = await item.mobileAuctionImages()
      const videos = await item.mobileAuctionVideos()
      const skuImages = await item.skuImages()
      const descImages = await item.mobileDescImages()
      if (images.length) {
        zip.folder('商品主图')
        for (const image of images) {
          const index = images.indexOf(image)
          loading.update(parseInt(index / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(image)
          const blob = await response.blob()
          zip.file(`商品主图/商品主图_${index + 1}.jpg`, blob)
        }
      }
      if (videos.length) {
        zip.folder('商品视频')
        for (const video of videos) {
          const index = videos.indexOf(video)
          loading.update(parseInt((index + images.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(video.url)
          const blob = await response.blob()
          zip.file(`商品视频/商品视频_${index + 1}.mp4`, blob)
        }
      }
      if (skuImages.length) {
        zip.folder('SKU图片')
        for (const skuImage of skuImages) {
          const index = skuImages.indexOf(skuImage)
          loading.update(parseInt((index + images.length + videos.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          if (typeof skuImage.image!=='undefined' && skuImage.image){
            const response = await fetch(skuImage.image)
            const blob = await response.blob()
            zip.file(`SKU图片/SKU图片_${skuImage.name}.jpg`, blob)
          }
        }
      }
      if (descImages.length) {
        zip.folder('详情图片')
        for (const descImage of descImages) {
          const index = descImages.indexOf(descImage)
          loading.update(parseInt((index + images.length + videos.length + skuImages.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(descImage)
          const blob = await response.blob()
          zip.file(`详情图片/详情图片_${index + 1}.jpg`, blob)
        }
        const langImag = await joinImages(descImages)
        if (langImag) {
          zip.folder('详情图片(长图)')
          const response = await fetch(langImag)
          const blob = await response.blob()
          zip.file(`详情图片(长图)/详情图片(长图)_1.jpg`, blob)
        }
      }
      loading.hide()
      message.success('全部下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端主图+主图视频+SKU图片+详情图片_ID${item.itemId()}.zip`)
      })
    },
  },
  {
    name: '下载全部(不归类)',
    tips: '一次性下载商品主图、主图视频、SKU图片、详情图片,所有资源在一个文件夹内',
    func: async () => {
      if (!isLogin({ emit }, __option)) return
      const loading = instance.proxy.$refs.loading
      loading.show('正在下载全部...')
      loading.update(0)
      const zip = new JSZip()
      const images = await item.auctionImages()
      const videos = await item.auctionVideos()
      const skuImages = await item.skuImages()
      const descImages = await item.descImages()

      if (images.length) {
        for (const image of images) {
          const index = images.indexOf(image)
          loading.update(parseInt(index / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(image)
          const blob = await response.blob()
          zip.file(`商品主图_${index + 1}.jpg`, blob)
        }
      }
      if (videos.length) {
        for (const video of videos) {
          const index = videos.indexOf(video)
          loading.update(parseInt((index + images.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(video.url)
          const blob = await response.blob()
          zip.file(`商品视频_${index + 1}.mp4`, blob)
        }
      }
      if (skuImages.length) {
        for (const skuImage of skuImages) {
          const index = skuImages.indexOf(skuImage)
          loading.update(parseInt((index + images.length + videos.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          if (typeof skuImage.image!=='undefined' && skuImage.image){
            const response = await fetch(skuImage.image)
            const blob = await response.blob()
            zip.file(`SKU图片_${skuImage.name}.jpg`, blob)
          }
        }
      }
      if (descImages.length) {
        for (const descImage of descImages) {
          const index = descImages.indexOf(descImage)
          loading.update(parseInt((index + images.length + videos.length + skuImages.length) / (videos.length + images.length + skuImages.length + descImages.length) * 100))
          const response = await fetch(descImage)
          const blob = await response.blob()
          zip.file(`详情图片_${index + 1}.jpg`, blob)
        }
        const langImag = await joinImages(descImages)
        if (langImag) {
          const response = await fetch(langImag)
          const blob = await response.blob()
          zip.file(`详情图片(长图)_1.jpg`, blob)
        }
      }
      loading.hide()
      message.success('全部下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_PC端主图+主图视频+SKU图片+详情图片_ID${item.itemId()}(不分类).zip`)
      })
    },
  },
  {
    name: '下载主图&视频',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return

      const loading = instance.proxy.$refs.loading
      loading.show('正在下载主图&视频...')
      loading.update(0)
      const images = await item.mobileAuctionImages()
      const videos = await item.mobileAuctionVideos()
      const zip = new JSZip()
      if (images.length > 0) {
        zip.folder('商品主图')
        for (const image of images) {
          const index = images.indexOf(image)
          loading.update(parseInt(index / (videos.length + images.length) * 100))
          const response = await fetch(image)
          const blob = await response.blob()
          zip.file(`商品主图/商品主图_${index + 1}.jpg`, blob)
          loading.update(parseInt((index + 1) / (videos.length + images.length) * 100))
        }
      }
      if (videos.length > 0) {
        zip.folder('商品视频')
        for (const video of videos) {
          const index = videos.indexOf(video)
          loading.update(parseInt((index + videos.length + 1) / (videos.length + images.length) * 100))
          const response = await fetch(video.url)
          const blob = await response.blob()
          zip.file(`商品视频/商品视频_${index + 1}.mp4`, blob)
          loading.update(parseInt((index + 1 + videos.length + 1) / (videos.length + images.length) * 100))
        }
      }
      loading.hide()
      message.success('主图&视频下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端主图&视频_ID${item.itemId()}_.zip`)
      })
    },
  },
  {
    name: '下载主图',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return

      const loading = instance.proxy.$refs.loading
      loading.show('正在下载主图...')
      loading.update(0)
      const images = await item.mobileAuctionImages()
      if (!images.length) {
        loading.hide()
        message.error('该商品没有主图！')
        return
      }
      const zip = new JSZip()
      for (const image of images) {
        const index = images.indexOf(image)
        loading.update((index / images.length * 100).toFixed(2))
        const response = await fetch(image)
        const blob = await response.blob()
        zip.file(`商品主图_${index + 1}.jpg`, blob)
        // zip.file(`主图_${index}.jpg`, image)
        loading.update(((index + 1) / images.length * 100).toFixed(2))
      }
      loading.hide()
      message.success('主图下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端主图_ID${item.itemId()}_.zip`)
      })
    },
  },
  {
    name: '下载视频',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return

      const loading = instance.proxy.$refs.loading
      loading.show('正在下载视频...')
      loading.update(0)
      const videos = await item.mobileAuctionVideos()
      if (!videos.length) {
        loading.hide()
        message.error('该商品没有视频！')
        return
      }
      const zip = new JSZip()
      for (const video of videos) {
        const index = videos.indexOf(video)
        loading.update((index / videos.length * 100).toFixed(2))
        const response = await fetch(video.url)
        const blob = await response.blob()
        zip.file(`商品视频_${index + 1}.mp4`, blob)
        loading.update(((index + 1) / videos.length * 100).toFixed(2))
      }
      loading.hide()
      message.success('视频下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端视频_ID${item.itemId()}.zip`)
      })
    },
  },
  {
    name: '下载SKU图',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return

      const loading = instance.proxy.$refs.loading
      loading.show('正在下载SKU图...')
      loading.update(0)
      const zip = new JSZip()
      const skuImages = await item.skuImages()
      for (const skuImage of skuImages) {
        const index = skuImages.indexOf(skuImage)
        loading.update((index / skuImages.length * 100).toFixed(2))
        const response = await fetch(skuImage.image)
        const blob = await response.blob()
        zip.file(`SKU图_${index + 1}_${skuImage.name}.jpg`, blob)
        loading.update(((index + 1) / skuImages.length * 100).toFixed(2))
      }
      loading.hide()
      message.success('SKU图下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端SKU图_ID${item.itemId()}.zip`)
      })
    },
  },
  {
    name: '下载详情图',
    func: async () => {
      if (!isLogin({ emit }, __option))
        return

      const loading = instance.proxy.$refs.loading

      loading.show('正在下载SKU图...')
      loading.update(0)
      const zip = new JSZip()
      const descImages = await item.mobileDescImages()
      if (!descImages.length) {
        loading.hide()
        message.error('该商品没有详情图！')
      }
      for (const descImage of descImages) {
        const index = descImages.indexOf(descImage)
        loading.update((index / descImages.length * 100).toFixed(2))
        const response = await fetch(descImage)
        const blob = await response.blob()
        zip.file(`详情图_${index + 1}.jpg`, blob)
      }
      loading.hide()
      message.success('详情图下载完成！')
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `星察数据_移动端详情图_ID${item.itemId()}.zip`)
      })
    },
  },
]
</script>

<template>
  <a-dropdown>
    <template #overlay>
      <a-menu>
        <a-menu-item v-for="item in pcDownload" :key="item.name" style="font-size: 12px;color: #444;" @click="item.func">
          <!--            <a style="color: #666;font-size: 12px;" @click="item.func"> -->
          {{ item.name }}
          <a-tooltip v-if="typeof item.tips != 'undefined'" placement="top">
            <template #title>
              <span style="color: 12px;">{{ item.tips }}</span>
            </template>
            <QuestionCircleOutlined />
          </a-tooltip>
          <!--            </a> -->
        </a-menu-item>
      </a-menu>
    </template>
    <div class="inner-box bold btn">
      <span>移动端下载<CaretDownOutlined /></span>
    </div>
  </a-dropdown>
  <canvas ref="canvas" width="750" height="0" style="display: none;"></canvas>
  <loading-modal ref="loading" />
</template>

<style scoped>

</style>
